#include "LookupWidget.h"
#include "qlitehtmlbrowser/QLiteHtmlBrowser.h"

#ifdef HasWebEngine
#include <QWebEngineView>
#endif

#include "ui_LookupWidget.h"

LookupWidget::LookupWidget(QWidget* parent)
    : QWidget(parent), ui(new Ui::LookupWidget) {
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint |
                   Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    m_hideTimer = new QTimer(this);
    m_hideTimer->setInterval(2000);
    connect(m_hideTimer, &QTimer::timeout, this, [this]() {
        hide();
        m_hideTimer->stop();
    });

#ifdef HasWebEngine
    m_view = new QWebEngineView(this);
#else
    m_view = new QLiteHtmlBrowser(this);
#endif
    ui->trans_page->layout()->addWidget(m_view);
}

LookupWidget::~LookupWidget() { delete ui; }

void LookupWidget::setContent(const QString& content) {
    static const QRegularExpression re(
        R"(<link\b[^>]*>)", QRegularExpression::CaseInsensitiveOption);
    auto html = content;
    html.remove(re);
#ifdef HasWebEngine
    m_view->setHtml(html);
#else
    m_view->setHtml(html);
#endif
}

void LookupWidget::moveAndExplain(QString msg, int type, QPoint pos) {
    if (type == Qt::RightButton) {
        ui->stackedWidget->setCurrentWidget(ui->anki_page);
    } else if (type == Qt::LeftButton) {
        ui->stackedWidget->setCurrentWidget(ui->trans_page);
        QFile cssfile(":/Res/rank.css");
        QString css;
        if (cssfile.open(QFile::ReadOnly)) {
            css = QString("<style>%1</style>").arg(QString(cssfile.readAll()));
            cssfile.close();
        }
        QString mdxQueryResult = msg;
        setContent(css + mdxQueryResult);
    }
    // move(pos);
    move(500, 500);
    show();
}

#if (QT_VERSION <= QT_VERSION_CHECK(6, 0, 0))
void LookupWidget::enterEvent(QEvent*) { m_hideTimer->stop(); }
#else
void LookupWidget::enterEvent(QEnterEvent*) { m_hideTimer->stop(); }
#endif

void LookupWidget::leaveEvent(QEvent*) { m_hideTimer->start(); }


bool LookupWidget::event(QEvent *e)
{
        if (e->type() == QEvent::WindowDeactivate) {
        hide();
        }else if(e->type() == QEvent::Show){
activateWindow();
        }
        return QWidget::event(e);
}
